import re
import pymongo
import common.gyblog as log
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.chrome.service import Service as ChromeService

LOG = log.get_logger()
SERVICE = ChromeService(executable_path="../common/chromedriver.exe")
CONNECTION_STR = 'mongodb://192.168.0.196:27017/?readPreference=primary&appname=MongoDB%20Compass%20Community&ssl=false'
# CONNECTION_STR = 'mongodb://192.168.0.196:27017/'
DATA_BASE = 'javbook_new'  # 数据库名
DB_COL = '1pondo'  # 表名
SERIES = '1pondo'
YEAR = '2023'
NUMS = ['123123-001', '112523-001', '110123-001', '102523-001', '103123-001', '101123-001', '100923-001', '102823-001',
        '100823-001', '092923-001', '101823-001', '100723-001', '093023-001', '091523-001', '091923-001', '092023-001',
        '082923-001', '091323-001', '090523-001', '082223-001', '082323-001', '090123-001', '082623-001', '082523-001',
        '092723-001', '092323-001', '081923-001', '081623-001', '082123-001', '080123-001', '081423-001', '080823-001',
        '081023-001', '081123-001', '072623-001', '071923-001', '070623-001', '070423-001', '061723-001', '062123-001',
        '062823-001', '062723-001', '070523-001', '070223-001', '060923-001', '060323-001', '060223-001', '060123-001',
        '053023-001', '060623-001', '052623-001', '050723-001', '050423-001', '042923-001', '050323-001', '043023-001',
        '042723-001', '050223-001', '041123-001', '040523-001', '022423-001', '032123-001', '021823-001', '021723-001',
        '021223-001', '021123-001', '020423-001', '013123-001', '020323-001', '012723-001', '012523-001', '012623-001',
        '012423-001', '011723-001', '021023-001', '011823-001', '010523-001']


def save_tor(num):
    # 信任链接
    url = 'https://sukebei.nyaa.si/?f=2&c=0_0&q={}-CARIB'.format(num)
    # 创建 WebDriver 对象
    driver = webdriver.Chrome(service=SERVICE)
    driver.get(url)
    # 使用 XPath 定位元素
    elements = driver.page_source
    tors = re.findall("magnet:\?xt=urn:.*?&amp", elements)

    # 连接数据库
    db_client = pymongo.MongoClient(CONNECTION_STR)
    db_database = db_client[DATA_BASE]
    db_col = db_database[DB_COL]

    if len(tors) == 0:
        print('{}：没有找到tor'.format(url))
        LOG.info('{}：没有找到tor'.format(url))
    else:
        query = {'num': num}
        new_values = {"$set": {"thz_tor": tors[0]}}
        db_col.update_one(query, new_values)
        print('已插入thz_tor in {}'.format(url))
        LOG.info('已插入thz_tor in {}'.format(url))
    driver.close()
    db_client.close()


def seek_subebei_by_num(num):
    # 连接数据库
    db_client = pymongo.MongoClient(CONNECTION_STR)
    db_database = db_client[DATA_BASE]
    db_col = db_database[DB_COL]
    # 查询
    query = {'num': num}
    projection = {'_id': 0, 'thz_tor': 1}
    query_ans = list(db_col.find(query, projection))
    # 关闭数据库连接
    db_client.close()
    # 结果处理
    if len(query_ans) == 1:
        if query_ans[0]['thz_tor'] == '':
            save_tor(num)
        else:
            print('{}已有磁力，跳过'.format(num))
            LOG.info('{}已有磁力，跳过'.format(num))
    elif len(query_ans) == 0:
        print('在数据库中没有搜到：{}'.format(num))
        LOG.info('在数据库中没有搜到：{}'.format(num))
    else:
        print('在数据库中搜到多个：{}'.format(num))
        LOG.info('在数据库中搜到多个：{}'.format(num))
    db_client.close()


def query_tor_by_names(names):
    # 连接数据库
    db_client = pymongo.MongoClient(CONNECTION_STR)
    db_database = db_client[DATA_BASE]
    db_col = db_database[DB_COL]

    ans = []
    error_ans = []

    for name in names:
        # 查询
        query = {'num': name}
        projection = {'_id': 0, 'thz_tor': 1}
        query_ans = list(db_col.find(query, projection))
        if query_ans[0]['thz_tor'] == '':
            error_ans.append(name)
        else:
            ans.append(query_ans[0]['thz_tor'])
    print('搜索到的磁力：')
    for a in ans:
        if a != '':
            print(a)
    print('未搜索到的番号：')
    for e in error_ans:
        print(e)
    print('共{}个，{}有tor,{}没有'.format(len(names), len(ans), len(error_ans)))
    db_client.close()


if __name__ == '__main__':
    # for num in NUMS:
    #     seek_subebei_by_num(num)

    query_tor_by_names(NUMS)
